<template>
  <div class="portal-view" :class="previewMode == 'pc' ? 'pcMode' : ''">
    <div class="portal-view-tips">
      <el-radio-group v-model="previewMode">
        <el-radio-button label="mobile">{{ $t('setting.buttonSet.text10') }}</el-radio-button>
        <el-radio-button label="pc">{{ $t('task.record.pcEnd') }}</el-radio-button>
      </el-radio-group>
      <div v-if="isMultiLanguage" class="portal-view-language">
        <!-- <el-dropdown>
          <div class="icon-box">
            <span class="door-language">{{ currentLanguageName }}</span>
            <i class="el-icon-arrow-down"></i>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="v in languageList"
              :key="v.code"
              @click.native="changeLanguage(v)"
            >
              {{ v.remark }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->
        <BaseLanguageDropdown
          class="flow-preview-header-translate"
          :options="languageList"
          :lang="formPreviewLocale"
          @change="changeLocale"
        />
      </div>
    </div>
    <div class="phone-box">
      <div class="portal-view-header">
        <h3 class="doorName">{{ doorName }}</h3>
      </div>
      <div class="portal-view-main">
        <mform-preview
          :value="previewFields"
          :theme-colour="themeColour"
          :is-only-preview="true"
          :preview-mode="previewMode"
        />
        <ul class="portal-view-main-doorTab">
          <li
            v-for="(v, i) in doorTabBar"
            :key="i"
            class="portal-view-main-doorTab-item"
            :style="{ color: v.value == checkModular ? themeColour : '#595959' }"
            @click="tabClick(v)"
          >
            <i
              :class="[
                'portal-view-main-doorTab-item-icon',
                'iconfont',
                v.icon,
              ]"
            ></i>
            <span class="portal-view-main-doorTab-item-title">
              {{ transformI18n(`portal.${v.value}`, formPreviewLocale) }}
            </span>
          </li>
        </ul>
      </div>
      <div class="portal-view-bar">
        <span></span>
      </div>
    </div>
    <div class="phone-edit">
      <div class="phone-edit__content">
        <div
          v-if="isHavePortalPageSetAuth()"
          id="multiLanguageRef"
          ref="multiLanguageRef"
          class="phone-edit__bgc"
        >
          <div class="portal-setting-header-row">
            <div class="portal-setting-header-row-btns">
              <el-button  class="build" type="primary" @click="handleJumpSetting" style="width:124px;height:40px;">
                {{ $t('portal.enterBuildingPage') }}
              </el-button>
            </div>
          </div>
        </div>
        <div class="portal-setting-delete">
          <el-button
            v-if="isNoDefaultTemplate && isHavePortalPageSetAuth()"
            class="portal-setting-delete-btn"
            plain
            style="width:40px;height:40px;"
            @click="handleClickDelTemplate"
          >
            <i class="iconfont icon-qingkongshanchu"></i>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/** vue */
import {
  reactive,
  onMounted,
  computed,
  ref,
  inject,
  toRefs,
} from 'vue';

/* api */
import { getDoorTypeFieldList } from '@src/api/PortalApi.ts';

/** util */
import * as FormUtil from '@src/mform/util';
import Platform from '@src/util/platform.ts';
import BaseLanguageDropdown from '@src/component/common/BaseLanguageDropdown/index'
import { useLocaleProvide } from '@hooks/useLocale'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
import { transformI18n } from '@src/locales/index.ts';
import { getCurrentInstance } from 'vue';
import { isHavePortalPageSetAuth } from '@service/AuthService'
import { isDevelopment } from '@src/util/platform';
import { MessageBox } from 'element-ui';
import i18n from '@src/locales'
/* mixin */
import { VersionControlIMMixin, VersionControlLinkCMixin } from '@src/mixins/versionControlMixin';

export default {
  name: 'PortalView',
  components: {
    BaseLanguageDropdown
  },
  mixins: [VersionControlIMMixin, VersionControlLinkCMixin],
  props: {
    isOpenRegister: {
      type: Boolean,
      default: false,
    },
    tenantId: {
      type: String,
      default: '',
    },
    doorType: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props) {
    
    const instance = getCurrentInstance();
    const languagesList = inject('languagesList');
    const editDoorType = inject('editDoorType');
    const doorTypeId = computed(() => props.doorType?.id ?? '');
    const languageList = computed(() => {
      let languageMaps = languagesList.value;
      let language = (props?.doorType?.setting?.language ?? []).map(
        v => v.code
      );
      return languageMaps.filter(v => language.includes(v.code));
    });
    const { locale: formPreviewLocale, setFormPreviewLocale } = useLocaleProvide('formPreviewLocale');
    const { isOpenMultiLanguage } = useFormMultiLanguage()
    function changeLocale(e){
      console.log(e, 'eee')
      setFormPreviewLocale(e)
    }
    const doorName = computed(() => {
      let zh_CN_NAME = props?.doorType?.zh_CN_NAME ?? '';
      const selectCode = languagesList.value.filter(item => item.languageKey == formPreviewLocale.value)[0]?.languageKey
      let doorName = props?.doorType?.setting?.doorNameLanguage[selectCode] ?? zh_CN_NAME;
      return doorName;
    });

    const isMultiLanguage = inject('isMultiLanguage');

    const tenantId = computed(() => {
      props?.tenantId ?? '';
    });

    const isOpenRegister = computed(() => {
      props?.isOpenRegister ?? false;
    });

    const themeColour = computed(() => {
      return (
        props.doorType?.setting?.doorStyle?.themeColour?.split(',')[0] ?? ''
      );
    });

    const isNoDefaultTemplate = computed(() => props.doorType?.defaultType === 1);

    const previewFields = computed(()=>{
      // 选中当前tab进行数据匹配
      let modular = state.checkModular
      let previewFields = state.allFields.filter(field => field.modular == modular);

      previewFields = !isOpenRegister.value
        ? previewFields.filter(v => v.formType !== 'productRegister')
        : previewFields;

      return FormUtil.initializeSetting(previewFields);
    })
    
    const state = reactive({
      previewMode: 'mobile',
      allFields: [],
      doorTabBar: [],
      checkModular:''
    });
    
    const getHomeFieldList = () => {
      getDoorTypeFieldList({
        tenantId: tenantId.value,
        typeId: doorTypeId.value,
        modular: '',
        draft: 0,
      }).then(result => {
        if (result.code == 200) {
          const data = result?.data || [];
          let doorTabBar = data.find(field => field.formType == 'tabbar')?.setting?.list ?? [];
          
          state.doorTabBar = doorTabBar.filter(v=>v.isVisible).filter(v => {
            
            // 商城需要根据版本控制
            if (v.value == 'market') {
              return instance?.proxy?._isShowLinkCShop
            }
            
            return v
          })
          state.allFields = data.filter(v => {
            // 在线客服字段根据版本控制
            if (v.formType == 'im') {
              return instance?.proxy?._isShowIMModule
            }
            
            return v
          })
          state.checkModular = state.doorTabBar[0]?.value
        } else {
          Platform.alert(result.msg);
        }
      });
    };

    const handleJumpSetting = () => {
      const resourcePrefix = isDevelopment() ? '' : '/shb/home';
      window.location.href = `${resourcePrefix}/portal/getDoorConfigPage?id=${doorTypeId.value}`;
    };

    // 删除门户
    const handleClickDelTemplate = v => {
      MessageBox.confirm(
        i18n.t('portal.portalTip3'),
        i18n.t('portal.portalTip4'),
        {
          confirmButtonText: i18n.t('common.base.confirm'),
          cancelButtonText: i18n.t('common.base.cancel'),
          type: 'warning',
        }
      )
        .then(() => {
          const params = {
            id: doorTypeId.value,
          };
          editDoorType({ editType: 'delete', params });
        })
        .catch(err => {
          console.log(err);
        });
    };

    const tabClick = v =>{
      state.checkModular = v.value
    }

    onMounted(() => {
      getHomeFieldList();
    });

    return {
      ...toRefs(state),
      doorName,
      languageList,
      previewFields,
      isMultiLanguage,
      themeColour,
      tabClick,
      formPreviewLocale,
      changeLocale,
      isOpenMultiLanguage,
      transformI18n,
      handleJumpSetting,
      isHavePortalPageSetAuth,
      handleClickDelTemplate,
      isNoDefaultTemplate
    };
  },
};
</script>

<style scoped lang="scss">
.portal-view {
  width: 400px;
  max-height: 100vh;
  position: relative;
  box-sizing: border-box;
  padding-bottom: 16px;
  overflow-x: scroll;
  margin: 0 16px;
  &.pcMode {
    width: 548px;
    .phone-box {
      width: 548px;
      padding: 0;
      border-radius: 0;
      max-height: calc(100% - 120px);
      .portal-view-header, .portal-view-bar {
        display: none;
      }
      .portal-view-main {
        height: 100%;
      }
    }
  }
  &-tips {
    font-size: 14px;
    font-weight: bold;
    padding: 12px 0;
    color: rgba(0, 0, 0, 0.65);
    text-align: center;
    position: relative;
    ::v-deep .el-radio-group label .el-radio-button__inner {
      width: 100px;
      overflow: hidden;
    }
    .portal-view-language {
      width: 100px;
      position: absolute;
      right: 0px;
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      .icon-box {
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        .door-language{
          font-weight: normal;
        }

        .el-icon-arrow-down{
          font-size: 18px;
          margin-left: 6px;
        }
      }
    }
  }

  .phone-box {
    width: 400px;
    max-height: 722px;
    height: calc(100vh - 120px);
    padding: 12px;
    box-sizing: border-box;
    background: #fcfdfe;
    border-radius: 25px;

    .portal-view-header {
      height: 62px;
      width: 100%;
      background: url(../../../assets/img/portalViewHeader.png) no-repeat;
      background-size: 100%;
      display: flex;
      justify-content: center;
      align-items: flex-end;
      .doorName {
        width: 250px;
        text-align: center;
        @include text-ellipsis();
      }
    }

    .portal-view-main {
      height: calc(100% - 62px - 34px);
      width: 100%;
      background: #ffffff;
      position: relative;
      display: flex;
      flex-direction: column;

      &-doorTab {
        width: 100%;
        height: 52px;
        background: #ffffff;
        display: flex;
        justify-content: space-around;

        &-item {
          height: 100%;
          width: 25%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          text-align: center;
          font-size: 12px;
          color: #595959;

          &.active {
            color: $color-primary-light-6;
          }

          &-icon {
          }

          &-title {
          }
        }
      }
    }

    .portal-view-bar {
      width: 100%;
      height: 34px;
      display: flex;
      align-items: center;
      justify-content: center;
      span {
        width: 127px;
        height: 6px;
        background: #454545;
        box-shadow: 0px 4px 16px 0px rgba(0, 0, 0, 0.1);
        border-radius: 3px;
      }
    }
  }
  .phone-edit {
    position: fixed;
    bottom: 0px;
    left: 208px;
    right: 400px;
    background-color: #fff;
    height: 65px;
    min-width: 548px;
    .phone-edit__content {
      display: flex;
      justify-content: center;
      line-height: 65px;
      .phone-edit__bgc {
        .build {
          padding:6px 15px;
        }
      }
      .portal-setting-delete {
        margin-left: 10px;
        .portal-setting-delete-btn {
          padding: 10px;
          i {
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>

<style>
.form-im-preview {
  /* right: calc(50% - 60px) !important; */
}
</style>
